﻿using System;
using System.Threading;
using System.Windows;

namespace CInChat.UI
{
    /// <summary>
    /// Interaction logic for LoginWindow.xaml
    /// </summary>
    public partial class LoginWindow : Window
    {
        public LoginWindow() {
            InitializeComponent();
            this.Loaded += loginWindow_Loaded;
        }

        private void loginWindow_Loaded(object sender, RoutedEventArgs e) {
            this.txtUser.Focus();
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e) {
            this.IsEnabled = false;
            ThreadPool.QueueUserWorkItem(new WaitCallback(authenticateUser), new User(txtUser.Text, txtPassword.Password));
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e) {
            this.DialogResult = false;
            this.Close();
        }

        private void authenticateUser(object state) {
            User user = state as User;
#if DEBUG
            App.User = user.UserName;
            this.Dispatcher.Invoke(new Action(delegate() {
                this.DialogResult = true;
                this.Close();
            }));
#else
            if (LdapLogin.IsValidUser("CIN", user.UserName, user.Password)) {
                App.User = user.UserName;
                this.Dispatcher.Invoke(new Action(delegate() {
                    this.DialogResult = true;
                    this.Close();
                }));
            } else {
                MessageBox.Show("Não foi possível autenticar o usuário informado.");
                this.Dispatcher.Invoke(new Action(delegate() { this.IsEnabled = true; }));
            }
#endif
        }
    }

    class User
    {
        public string UserName { get; set; }
        public string Password { get; set; }

        public User(string user, string password) {
            this.UserName = user;
            this.Password = password;
        }
    }
}
